package com.yjz.study.http.intercept

import com.yjz.common.restful.Interceptor
import com.yjz.common.restful.RequestInfo
import com.yjz.common.util.SPUtil
import com.yjz.log.JLog
import com.yjz.study.account.AccountManager
import com.yjz.study.cons.SPKeys

/**
 *作用 : 请求信息拦截器
 *作者 : yjz
 *时间 : 2025/2/11 16:45
 */
class RequestInfoInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Boolean {
        val request = chain.request()
        val response = chain.response()
        if (chain.isRequestPeriod) { // chain.isRequestPeriod表示请求还有相应结果，是请求发出阶段
            val boardingPass = AccountManager.getBoardingPass()
            request.addHeader(SPKeys.BOARDING_PASS, boardingPass)
            request.addHeader("auth-token", "MjAyMC0wNi0yMyAwMzoyNTowMQ==")
        } else if (response != null) {
            val outputBuilder = StringBuilder()
            val httpMethod: String =
                if (request.httpMethod == RequestInfo.METHOD.GET) "GET" else "POST"
            val requestUrl: String = request.endPointUrl()
            outputBuilder.append("\n$requestUrl==>$httpMethod\n")

            if (request.headers != null) {
                outputBuilder.append("【headers\n")
                request.headers!!.forEach(action = {
                    outputBuilder.append(it.key + ":" + it.value)
                    outputBuilder.append("\n")
                })
                outputBuilder.append("headers】\n")
            }

            if (request.parameters != null && request.parameters!!.isNotEmpty()) {
                outputBuilder.append("【parameters==>\n")
                request.parameters!!.forEach(action = {
                    outputBuilder.append(it.key + ":" + it.value + "\n")
                })
                outputBuilder.append("parameters】\n")
            }

            outputBuilder.append("【response==>\n")
            outputBuilder.append(response.rawData + "\n")
            outputBuilder.append("response】\n")

            JLog.eTag("Interceptor:", outputBuilder.toString())
        }
        return false
    }
}